<template>
  <div :id="id" :style="{ height: height, width: width }" />
</template>

<script>
import echarts from "echarts";
export default {
  props: {
    id: {
      type: String,
      default: "chart",
    },
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "400px",
    },
    questionTimeData: {
      type: Object,
      default: function () {
        return {};
      },
    },
    title: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      chart: null,
      echartData: [],
      resizeTimer: null,
    };
  },
  watch: {
    questionTimeData: {
      handler(newV) {
        this.echartData = newV;
        this.initChart();
      },
      deep: true,
    },
  },
  mounted() {
    this.echartData = this.questionTimeData;
    console.log(this.questionTimeData);
    this.initChart();
    window.addEventListener("resize", this.erchartResize);
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart = null;
  },
  methods: {
    erchartResize() {
      if (this.resizeTimer) clearTimeout(this.resizeTimer);
      this.resizeTimer = setTimeout(() => {
        this.chart.resize();
      }, 100);
    },
    initChart() {
      this.chart = echarts.init(document.getElementById(this.id));
      const option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
            crossStyle: {
              color: "#999",
            },
          },
        },
        xAxis: [
          {
            type: "category",
            data: this.echartData.dateData,
            axisPointer: {
              type: "shadow",
            },
          },
        ],
        yAxis: [
          {
            type: "value",
            name: "题目用时",
            axisLabel: {
              formatter: "{value}小时",
            },
          },
        ],
        series: [
          {
            name: "题目用时",
            type: 'bar',
            barWidth: "60%",
            itemStyle: {
              color: "#3398DB",
            },
            data: this.echartData.timeData,
          },
        ],
      };
      this.chart.setOption(option);
    },
  },
  destroyed() {
    window.removeEventListener("resize", this.erchartResize);
  },
};
</script>
<style lang='stylus' scoped>
.chartsClass {
  padding-left: 1.2rem;
}
</style>
</script>